import React from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuth } from '../../contexts/AuthProvider'
import { LoadingScreen } from '../ui/LoadingScreen'

interface AuthGuardProps {
  children: React.ReactNode
}

export function AuthGuard({ children }: AuthGuardProps) {
  const { user, initializing } = useAuth()
  const location = useLocation()

  if (initializing) {
    return <LoadingScreen />
  }

  if (!user) {
    // Redirect to auth page with return URL
    return <Navigate to={`/auth/login?returnTo=${encodeURIComponent(location.pathname)}`} replace />
  }

  return <>{children}</>
}